//
//  OAuthViewController.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/13.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController ,UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    
    /**
    private let WEB_Client_ID = "186941684"
    private let WEB_Redirect_URL = "https://www.baidu.com"
    private let WEB_Client_Secret = "47e2efbaf0b3ba98bc83d4abc4a932ae"
    */
    
    
    private let WEB_Client_ID = "2551929163"
    private let WEB_Redirect_URL = "https://www.baidu.com"
    private let WEB_Client_Secret = "cc04b3428d09576cd49e2f56d04a1d35"
     /**
        App Key：2551929163
        App Secret：cc04b3428d09576cd49e2f56d04a1d35
    */
    
    // code
    private var code:String?
    
    // 页面加载时,访问授权页面
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=\(WEB_Client_ID)&redirect_uri=\(WEB_Redirect_URL)"
        let request = NSURLRequest(URL: NSURL(string: urlstring)!)
        webView.loadRequest(request)
    }
    
    
    // 访问授权界面
    func loadAccreditPage() {
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=\(WEB_Client_ID)&redirect_uri=\(WEB_Redirect_URL)"
        let request = NSURLRequest(URL: NSURL(string: urlstring)!)
        webView.loadRequest(request)
        
    }
    
    
    // 拦截访问请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let requeststring = request.URL!.absoluteString!
        // 前缀以https://api.weibo.com/的继续访问
        if requeststring.hasPrefix("https://api.weibo.com/") {
            return true
        }
        
        // 判断重定向
        if !requeststring.hasPrefix(WEB_Redirect_URL) {
            return false
        }
        
        // 如果是回调网站结果,分析数据,拉到code
        if let query = request.URL?.query {
            let codetag = "code="
            if query.hasPrefix(codetag) {
                code = (query as NSString).substringFromIndex(codetag.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
                loadAccessToken(code!)
            }
        } else {
            // 重新加载访问页面,点击取消的问题
            loadAccreditPage()
        }
        return false
    }
    
    
    // 获取访问令牌
    func loadAccessToken(code: String) {
        // 使用code获取访问令牌
        let params = [
            "code": code,
            "client_id": WEB_Client_ID,
            "redirect_uri": WEB_Redirect_URL,
            "grant_type": "authorization_code",
            "client_secret": WEB_Client_Secret
        ]
        
        // 登陆状态,设置全局变量
        UserAccount.loadAccessToken(params) { (user) -> () in
            if user != nil {
                userInfoShared = user!
                SVProgressHUD.dismiss()
                // 发送通知,切换根控制器,到欢迎界面
                NSNotificationCenter.defaultCenter().postNotificationName(viewControllerNotifi, object: "Welcome")
            }
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        
    }

    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    // 关闭窗口
    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss() 
    }
    
    
}
